package com.example.research.controller;

import com.example.research.dto.ApiResponse;
import com.example.research.dto.LoginRequest;
import com.example.research.dto.LoginResponse;
import com.example.research.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/auth")
@Validated
public class AuthController {

    @Autowired
    private AuthService authService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ApiResponse<LoginResponse> login(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            LoginResponse response = authService.login(loginRequest);
            return ApiResponse.success("登录成功", response);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 验证token
     */
    @PostMapping("/validate")
    public ApiResponse<Boolean> validateToken(@RequestParam String token) {
        try {
            boolean isValid = authService.validateToken(token);
            return ApiResponse.success(isValid);
        } catch (Exception e) {
            return ApiResponse.error("Token验证失败");
        }
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/me")
    public ApiResponse<?> getCurrentUser(@RequestHeader("Authorization") String authHeader) {
        try {
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                return ApiResponse.unauthorized("未提供有效的认证信息");
            }

            String token = authHeader.substring(7);
            if (!authService.validateToken(token)) {
                return ApiResponse.unauthorized("Token已过期或无效");
            }

            Object user = authService.getCurrentUser(token);
            return ApiResponse.success(user);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public ApiResponse<String> logout() {
        // 由于使用JWT，登出只需要前端删除token即可
        return ApiResponse.success("登出成功");
    }
}
